package cn.kgc.springday07.service.impl;

import cn.kgc.springday07.entity.User;
import cn.kgc.springday07.entity.UserRole;
import cn.kgc.springday07.form.UserForm;
import cn.kgc.springday07.mapper.UserMapper;
import cn.kgc.springday07.mapper.UserRoleMapper;
import cn.kgc.springday07.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 课工场
 * @date 2023/10/12
 * @description @Transactional
 * 1.@Transactional 注解使用位置
 * ElementType.TYPE,    类上   注解对该类中的方法全部生效
 * ElementType.METHOD  方法上  注解只对当前方法有效
 *
 * 2.@Transactional   注解属性
 * 1. propagation  Propagation   事务传播机制
 *   REQUIRED        需要使用事务
 *   SUPPORTS        支持使用事务
 *   REQUIRES_NEW    创建新的事务
 *
 * 2. isolation   Isolation.DEFAULT   事务的隔离级别
 * 1.READ_UNCOMMITTED    读未提交     脏读  幻读  不可重复读
 * A    2   INSERT       2
 * B        SELECT       3
 * 2.READ_COMMITTED      读已提交     幻读  不可重复读
 * A    2   INSERT       2
 * B        SELECT       2
 * 3.REPEATABLE_READ     可重复读  mysql数据库默认的事务隔离级别   幻读
 * A    2   INSERT       3
 * B        SELECT       2
 * 4.SERIALIZABLE        串行化    排队执行    效率最低
 * A    2   INSERT       3
 * B        SELECT       3  2
 * 3. rollbackFor                     设置事务回滚的异常类型
 * 4. noRollbackFor                  设置事务不回滚的异常类型
 */
@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;



    public UserMapper getUserMapper() {
        return userMapper;
    }

    @Override
    public List<User> getList() {
        List<User> users = userMapper.getList();
        return users;
    }

    //    @Transactional   //   使用事务控制该方法的执行
    @Override
    public Boolean addUser(UserForm userForm) {

        User user = new User();
        BeanUtils.copyProperties(userForm, user);
        //1. 将用户的基本信息添加到user表
        Integer integer = userMapper.addUser(user);
        Integer uid = user.getId();


        int a = 1 / 0;

        //2.将用户角色信息 添加到user_role
        List<Integer> rids = userForm.getRids();
        for (Integer rid : rids) {
            UserRole userRole = new UserRole();
            userRole.setRid(rid);
            userRole.setUid(uid);
            userRoleMapper.addUserRole(userRole);
        }

        return true;
    }
}
